﻿define(['jquery'], function ($) {
    var input = {};
    var container = {};
    var completed = {};
    var textChanged = {};
    var active = null;
    var url = '/Book/GetBookList';
    var selectedId = 'bookId';
    var bgColor = '#d1d1d1';
    //var selectedValue = {};

    //为当前活动元素添加背景
    var pointHover = function (active) {
        $(active).css("background", bgColor);
    };

    //去掉当前活动元素背景
    var pointBlur = function (active) {
        $(active).css("background", "none");
    };

    //按回车或鼠标点击选中
    var selected = function () {
        $(input).val($(active).text());
        $(input).attr(selectedId, $(active).attr(selectedId));
        myEvent.oncompleted();
        active = null;
        $(container).hide();
    };

    //事件
    var myEvent = {
        init: function () {
            this.mouseover();
            this.mousedown();
            this.onblur();
            this.keyup();
            //this.onchange();
        },
        mouseover: function () {
            $(container).on('mouseover', function (e) {
                var target = e.target || e.srcElement;
                if (target.className == "") {
                    if (active) {
                        pointBlur(active);
                    }
                    active = target;
                    pointHover(active);
                }
            });
        },
        mousedown: function () {
            $(container).on('mousedown', function () {
                selected();
            });
        },
        onblur: function () {
            //文本框失去焦点后
            $(input).on('blur', function () {
                $(container).hide();
            });
        },
        keyup: function () {
            $(input).on('keyup', function (ev) {
                var keyCode = ev.charCode || ev.keyCode;
                if (keyCode == (37 || 39))//按键为左右键时不做任何处理
                    return;
                switch (keyCode) {
                    case 13://Enter键
                        enter();
                        break;
                    case 27:
                        $(container).hide();
                        break;
                    case 38://上键
                        up();
                        break;
                    case 40://下键
                        down();
                        break;
                    default:
                        action.post();
                }
            });
            function up() {
                //container不为隐藏，则继续事件，否则活动元素为最后一个元素
                if ($(container)[0].style.display != 'none') {
                    //如果存在活动元素
                    if (active) {
                        var pre = $(active)[0].previousSibling;
                        //如果活动元素之前还有同级元素
                        if (pre) {
                            pointBlur(active);
                            active = pre;
                            pointHover(active);
                        }
                        else {
                            pointBlur(active);
                            active = null;
                            $(input).focus();
                        }
                        $(input).val($(active).text());
                    } else {
                        var last = $(container).find('ul li:last-child');
                        if (last) {
                            active = last;
                            pointHover(active);
                        }
                    }
                }
            };
            function down() {
                if ($(container)[0].style.display != 'none') {
                    if (active) {
                        var next = $(active)[0].nextSibling;
                        if (next) {
                            pointBlur(active);
                            active = next;
                            pointHover(active);
                        } else {
                            pointBlur(active);
                            active = null;
                            $(input).focus();
                        }
                    } else {
                        var first = $(container).find('ul li:first-child');
                        if (first) {
                            active = first;
                            pointHover(active);
                        }
                    }
                    $(input).val($(active).text());
                }
            };
            function enter() {
                if ($(container)[0].style.display != 'none') {
                    if (active) {
                        selected();
                    }
                }
            }
        },
        //onchange: function () {
        //    $(input).on('change', function () {
        //        if (!selectedValue) {
        //            $(input).removeAttr(selectedId);
        //        }
        //        if (textChanged)
        //            textChanged();
        //    });
        //},
        oncompleted: function () {
            if (completed) {
                var returnData = action.generateReturnData(active);
                //if (returnData)
                completed(returnData);
            }
        }
    };

    //搜索及返回数据操作
    var action = {
        //Container中HTML内容
        generateCode: function (data) {
            var result = '<ul>';
            for (var o in data) {
                result += '<li ' + selectedId + '=' + data[o]["Id"] + '>' + data[o]["Name"] + '</li>'
            }
            result += '</ul>';
            return result;
        },
        //ajax 提交，获取数据
        post: function () {
            $.ajax({
                type: "get",
                url: url,
                data: { bookName: $(input).val() },
                success: function (data) {
                    $(container).hide();
                    if (data.Count > 0) {
                        $(container).html(action.generateCode(data.Value));
                        $(container).show();
                    }
                }
            });
        },
        //触发选中事件后，返回的数据。
        generateReturnData: function () {
            return {
                Id: $(active).attr(selectedId),
                Name: $(active).text()
            };;
        }
    };

    //初始化时校验输入参数
    var valid = function (paras) {
        if (!paras.input) throw 'input is underfined';
        if (!paras.container) throw 'container is underfined';
        if (!$(paras.container)[0]) throw 'can not find container which named ' + $(paras.container).selector;
        //if (!paras.completed) throw 'completed function is not defined';
        if (paras.completed && typeof paras.completed != "function") throw 'completed is not a function ';
        //if (paras.textChanged && typeof paras.textChanged != "function") throw 'textChanged is not a function ';
        return true;
    };

    //初始化各变量值
    var initValues = function (paras) {
        if (valid(paras)) {
            input = paras.input;
            container = paras.container;
            completed = paras.completed;
            textChanged = paras.textChanged;
            bgColor = paras.bgColor || bgColor;
            url = paras.url || url;
            $(container).hide();
            $(input).attr('autocomplete', 'off');//关闭文本框默认的自动补全功能
        }
    };

    /*
     *初始化(input-绑定的文本框元素,container-绑定的容器,completed-选中完成事件)
     */
    var init = function (paras) {
        initValues(paras);//初始化变量值
        myEvent.init();//初始化事件
    }

    return {
        init: init
    };
});